/**
 * Wishlist Functions
 * 愿望清单功能
 * 
 * @package WP Bootstrap Woo
 */

(function($) {
    'use strict';

    const Wishlist = {
        init: function() {
            this.setupWishlistButtons();
            this.setupWishlistPage();
            this.loadWishlistFromStorage();
            this.updateWishlistCount();
        },

        // 设置愿望清单按钮
        setupWishlistButtons: function() {
            $(document).on('click', '.btn-wishlist', function(e) {
                e.preventDefault();
                
                const $button = $(this);
                const productId = $button.data('product-id');
                
                if (!productId) return;
                
                // 检查用户是否登录
                if (!wbw_ajax.is_user_logged_in) {
                    Wishlist.handleGuestWishlist($button, productId);
                    return;
                }
                
                const isInWishlist = $button.hasClass('in-wishlist');
                const action = isInWishlist ? 'remove' : 'add';
                
                Wishlist.toggleWishlistItem($button, productId, action);
            });
        },

        // 切换愿望清单项目
        toggleWishlistItem: function($button, productId, action) {
            $button.addClass('loading');
            
            const ajaxAction = action === 'add' ? 'wbw_add_to_wishlist' : 'wbw_remove_from_wishlist';
            
            $.ajax({
                url: wbw_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: ajaxAction,
                    product_id: productId,
                    nonce: wbw_ajax.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // 更新按钮状态
                        $button.toggleClass('in-wishlist');
                        
                        // 更新图标
                        const $icon = $button.find('i');
                        if ($button.hasClass('in-wishlist')) {
                            $icon.removeClass('feather-heart').addClass('feather-heart-filled');
                            Wishlist.showNotification('Added to wishlist', 'success');
                        } else {
                            $icon.removeClass('feather-heart-filled').addClass('feather-heart');
                            Wishlist.showNotification('Removed from wishlist', 'info');
                        }
                        
                        // 更新计数
                        Wishlist.updateWishlistCount(response.data.wishlist_count);
                        
                        // 如果在愿望清单页面，移除项目
                        if (action === 'remove' && $('.wishlist-page').length) {
                            $button.closest('.wishlist-item').fadeOut(function() {
                                $(this).remove();
                                Wishlist.checkEmptyWishlist();
                            });
                        }
                        
                    } else {
                        Wishlist.showNotification(response.data.message, 'error');
                    }
                },
                error: function() {
                    Wishlist.showNotification('Something went wrong. Please try again.', 'error');
                },
                complete: function() {
                    $button.removeClass('loading');
                }
            });
        },

        // 处理访客愿望清单（本地存储）
        handleGuestWishlist: function($button, productId) {
            const isInWishlist = $button.hasClass('in-wishlist');
            let guestWishlist = JSON.parse(localStorage.getItem('wbw_guest_wishlist') || '[]');
            
            if (isInWishlist) {
                // 从愿望清单移除
                guestWishlist = guestWishlist.filter(id => id != productId);
                $button.removeClass('in-wishlist');
                $button.find('i').removeClass('feather-heart-filled').addClass('feather-heart');
                Wishlist.showNotification('Removed from wishlist', 'info');
            } else {
                // 添加到愿望清单
                if (!guestWishlist.includes(productId)) {
                    guestWishlist.push(productId);
                    $button.addClass('in-wishlist');
                    $button.find('i').removeClass('feather-heart').addClass('feather-heart-filled');
                    Wishlist.showNotification('Added to wishlist', 'success');
                }
            }
            
            localStorage.setItem('wbw_guest_wishlist', JSON.stringify(guestWishlist));
            Wishlist.updateWishlistCount(guestWishlist.length);
        },

        // 设置愿望清单页面
        setupWishlistPage: function() {
            // 清空愿望清单
            $(document).on('click', '.clear-wishlist', function(e) {
                e.preventDefault();
                
                if (confirm('Are you sure you want to clear your wishlist?')) {
                    Wishlist.clearWishlist();
                }
            });
            
            // 移动到购物车
            $(document).on('click', '.move-to-cart', function(e) {
                e.preventDefault();
                
                const $button = $(this);
                const productId = $button.data('product-id');
                
                Wishlist.moveToCart($button, productId);
            });
            
            // 批量操作
            $('.select-all-wishlist').on('change', function() {
                $('.wishlist-item input[type="checkbox"]').prop('checked', $(this).is(':checked'));
            });
            
            $('.bulk-action-btn').on('click', function(e) {
                e.preventDefault();
                
                const action = $('.bulk-action-select').val();
                const selectedItems = $('.wishlist-item input[type="checkbox"]:checked');
                
                if (selectedItems.length === 0) {
                    alert('Please select items first.');
                    return;
                }
                
                if (action === 'remove') {
                    Wishlist.bulkRemove(selectedItems);
                } else if (action === 'move_to_cart') {
                    Wishlist.bulkMoveToCart(selectedItems);
                }
            });
        },

        // 从本地存储加载愿望清单状态
        loadWishlistFromStorage: function() {
            if (wbw_ajax.is_user_logged_in) return;
            
            const guestWishlist = JSON.parse(localStorage.getItem('wbw_guest_wishlist') || '[]');
            
            guestWishlist.forEach(productId => {
                const $button = $(`.btn-wishlist[data-product-id="${productId}"]`);
                if ($button.length) {
                    $button.addClass('in-wishlist');
                    $button.find('i').removeClass('feather-heart').addClass('feather-heart-filled');
                }
            });
            
            this.updateWishlistCount(guestWishlist.length);
        },

        // 更新愿望清单计数
        updateWishlistCount: function(count) {
            if (count !== undefined) {
                $('.wishlist-count').text(`(${count})`);
            } else {
                // 从服务器获取计数
                if (wbw_ajax.is_user_logged_in) {
                    $.ajax({
                        url: wbw_ajax.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'wbw_get_wishlist_count',
                            nonce: wbw_ajax.nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                $('.wishlist-count').text(`(${response.data.count})`);
                            }
                        }
                    });
                } else {
                    const guestWishlist = JSON.parse(localStorage.getItem('wbw_guest_wishlist') || '[]');
                    $('.wishlist-count').text(`(${guestWishlist.length})`);
                }
            }
        },

        // 移动到购物车
        moveToCart: function($button, productId) {
            $button.addClass('loading').text('Moving...');
            
            $.ajax({
                url: wbw_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'wbw_add_to_cart',
                    product_id: productId,
                    quantity: 1,
                    nonce: wbw_ajax.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // 从愿望清单移除
                        Wishlist.toggleWishlistItem($button.closest('.wishlist-item').find('.btn-wishlist'), productId, 'remove');
                        
                        // 更新购物车计数
                        if (window.WBW_WooCommerce) {
                            window.WBW_WooCommerce.updateCartCount(response.data.cart_count);
                        }
                        
                        Wishlist.showNotification('Product moved to cart!', 'success');
                    } else {
                        Wishlist.showNotification(response.data.message, 'error');
                    }
                },
                complete: function() {
                    $button.removeClass('loading').text('Add to Cart');
                }
            });
        },

        // 批量移除
        bulkRemove: function(selectedItems) {
            if (!confirm('Are you sure you want to remove selected items?')) return;
            
            selectedItems.each(function() {
                const $item = $(this).closest('.wishlist-item');
                const $wishlistBtn = $item.find('.btn-wishlist');
                const productId = $wishlistBtn.data('product-id');
                
                Wishlist.toggleWishlistItem($wishlistBtn, productId, 'remove');
            });
        },

        // 批量移动到购物车
        bulkMoveToCart: function(selectedItems) {
            let processed = 0;
            const total = selectedItems.length;
            
            selectedItems.each(function() {
                const $item = $(this).closest('.wishlist-item');
                const $addButton = $item.find('.move-to-cart');
                const productId = $addButton.data('product-id');
                
                setTimeout(() => {
                    Wishlist.moveToCart($addButton, productId);
                    processed++;
                    
                    if (processed === total) {
                        Wishlist.showNotification(`${total} items moved to cart!`, 'success');
                    }
                }, processed * 500); // 延迟处理避免服务器压力
            });
        },

        // 清空愿望清单
        clearWishlist: function() {
            if (wbw_ajax.is_user_logged_in) {
                $.ajax({
                    url: wbw_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'wbw_clear_wishlist',
                        nonce: wbw_ajax.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            $('.wishlist-item').fadeOut(function() {
                                $(this).remove();
                                Wishlist.checkEmptyWishlist();
                            });
                            Wishlist.updateWishlistCount(0);
                            Wishlist.showNotification('Wishlist cleared', 'info');
                        }
                    }
                });
            } else {
                localStorage.removeItem('wbw_guest_wishlist');
                $('.wishlist-item').fadeOut(function() {
                    $(this).remove();
                    Wishlist.checkEmptyWishlist();
                });
                Wishlist.updateWishlistCount(0);
                Wishlist.showNotification('Wishlist cleared', 'info');
            }
        },

        // 检查空愿望清单
        checkEmptyWishlist: function() {
            if ($('.wishlist-item').length === 0) {
                $('.wishlist-content').html(`
                    <div class="empty-wishlist">
                        <div class="empty-wishlist-content">
                            <i class="feather-heart"></i>
                            <h3>Your wishlist is empty</h3>
                            <p>Add items you love to your wishlist. Review them anytime and easily move them to the cart.</p>
                            <a href="${wbw_ajax.site_url}/shop" class="btn-continue-shopping">Continue Shopping</a>
                        </div>
                    </div>
                `);
            }
        },

        // 显示通知
        showNotification: function(message, type) {
            if (window.WBW_WooCommerce && typeof window.WBW_WooCommerce.showNotification === 'function') {
                window.WBW_WooCommerce.showNotification(message, type);
            } else {
                // 简单的alert作为后备
                alert(message);
            }
        },

        // 同步访客愿望清单到用户账户
        syncGuestWishlist: function() {
            const guestWishlist = JSON.parse(localStorage.getItem('wbw_guest_wishlist') || '[]');
            
            if (guestWishlist.length === 0) return;
            
            $.ajax({
                url: wbw_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'wbw_sync_guest_wishlist',
                    guest_wishlist: guestWishlist,
                    nonce: wbw_ajax.nonce
                },
                success: function(response) {
                    if (response.success) {
                        localStorage.removeItem('wbw_guest_wishlist');
                        Wishlist.updateWishlistCount();
                    }
                }
            });
        }
    };

    // 文档加载完成后初始化
    $(document).ready(function() {
        Wishlist.init();
        
        // 如果用户刚登录，同步访客愿望清单
        if (wbw_ajax.is_user_logged_in && localStorage.getItem('wbw_guest_wishlist')) {
            Wishlist.syncGuestWishlist();
        }
    });

    // 全局暴露
    window.Wishlist = Wishlist;

})(jQuery);

// 愿望清单相关CSS样式
const wishlistStyles = `
    .btn-wishlist {
        position: relative;
        transition: all 0.3s ease;
    }

    .btn-wishlist.loading::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 16px;
        height: 16px;
        border: 2px solid #fff;
        border-top: 2px solid transparent;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    .btn-wishlist.in-wishlist {
        color: #e74c3c;
    }

    .btn-wishlist.in-wishlist i {
        animation: heartBeat 1s ease-in-out;
    }

    @keyframes heartBeat {
        0% { transform: scale(1); }
        14% { transform: scale(1.3); }
        28% { transform: scale(1); }
        42% { transform: scale(1.3); }
        70% { transform: scale(1); }
    }

    @keyframes spin {
        0% { transform: translate(-50%, -50%) rotate(0deg); }
        100% { transform: translate(-50%, -50%) rotate(360deg); }
    }

    .empty-wishlist {
        text-align: center;
        padding: 80px 20px;
    }

    .empty-wishlist-content i {
        font-size: 64px;
        color: #ddd;
        margin-bottom: 20px;
    }

    .empty-wishlist-content h3 {
        margin-bottom: 15px;
        color: #666;
    }

    .empty-wishlist-content p {
        color: #999;
        margin-bottom: 30px;
        max-width: 400px;
        margin-left: auto;
        margin-right: auto;
    }

    .btn-continue-shopping {
        background: #007cba;
        color: #fff;
        padding: 12px 30px;
        border-radius: 6px;
        text-decoration: none;
        font-weight: 600;
        transition: background 0.3s ease;
    }

    .btn-continue-shopping:hover {
        background: #005a8b;
        color: #fff;
    }

    .wishlist-item {
        transition: opacity 0.3s ease;
    }

    .wishlist-item.removing {
        opacity: 0.5;
    }
`;

// 注入CSS样式
if (!document.getElementById('wishlist-styles')) {
    const styleSheet = document.createElement('style');
    styleSheet.id = 'wishlist-styles';
    styleSheet.textContent = wishlistStyles;
    document.head.appendChild(styleSheet);
}